package com.my.servlets;

import com.my.entity.User;
import com.my.user.service.IUserService;
import com.my.user.service.impl.UserServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class UploadServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        //上传
        try{
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(isMultipart){//判断前台的from是否有mutipart属性
                DiskFileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                //通过parseRequest解析form中的所有请求字段，并保存到items集合中

                //设置上传时用到的临时文件的大小DiskFileItemFactory
                factory.setSizeThreshold(10240);//设置临时缓冲文件大小为10KB
                factory.setRepository(new File("d:\\uploadtemp"));//设置临时目录，存放临时文件
                //控制上传单个文件的大小20KB
                upload.setSizeMax(20480);

                List<FileItem> items = upload.parseRequest(request);
                //遍历items中的数据
                Iterator<FileItem> iter = items.iterator();
                while(iter.hasNext()){
                    FileItem item = iter.next();
                    String itemName = item.getFieldName();
                    int sno = -1;
                    String sname = null;
                    //判断前台字段是普通form表单字段（sno、sname），还是文件字段
                    if(item.isFormField()){
                        if(itemName.equals("sno")){
                            sno = Integer.parseInt(item.getString("UTF-8"));
                        }else if(itemName.equals("sname")){
                            sname = item.getString("UTF-8");
                        }
                    }else{
                        //文件上传
                        //getFieldName()获取普通表单字段name值
                        //getName()获取文件名
                        String fileName = item.getName();

                        //限制文件类型
                        String ext = fileName.substring(fileName.indexOf("."));
                        if(!(ext.equals("png") || ext.equals("gif") || ext.equals("jpg"))){
                            System.out.println("文件格式不正确。");
                            return;//终止
                        }

                        //获取服务器路径
                        String path=request.getSession().getServletContext().getRealPath("upload");
                        File file = new File(path,fileName);

                        item.write(file);
                        System.out.println(fileName + "上传成功！");
                        return;
                    }
                }
            }
        }catch (FileUploadBase.SizeLimitExceededException e){
            System.out.println("上传的文件大小超过限制，不能超过20KB。");
        }
        catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
